//
//  MessageSendViewController.m
//  FVQuickMessage
//
//  Created by HoiChen on 16/8/18.
//  Copyright © 2016年 zty. All rights reserved.
//

#import "MessageSendViewController.h"
#import "CharDetailViewController.h"
@interface MessageSendViewController ()<EMChatManagerDelegate, UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *buddyList;
@property (nonatomic, strong) NSMutableArray *groupArray;
@end

@implementation MessageSendViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"通讯录";
    
    self.automaticallyAdjustsScrollViewInsets = YES;
    self.buddyList = [NSArray array];
    self.buddyList = [[EaseMob sharedInstance].chatManager buddyList];
    if (_buddyList.count == 0) {
        [[EaseMob sharedInstance].chatManager asyncFetchBuddyListWithCompletion:^(NSArray *buddyList, EMError *error) {
            _buddyList = buddyList;
        } onQueue:nil];
    }
    [self getGroupNames];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"+" style:UIBarButtonItemStyleDone target:self action:@selector(rightAction)];
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 20, WIDTH, HEIGHT) style:UITableViewStyleGrouped];
    [self.view addSubview:_tableView];
    _tableView.delegate = self;
    _tableView.dataSource  = self;
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:nil];
    
}
-(void)rightAction{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"添加请求好友信息" message:nil preferredStyle:UIAlertControllerStyleAlert];
    //好友名称
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = @"请添加好友名称";
    }];
    //附加信息
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = @"请添加请求";
        
    }];
    UITextField *userNameField = alert.textFields.firstObject;
    UITextField *descriptionField = alert.textFields.lastObject;
    //添加确定按钮
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if (userNameField.text.length == 0) {
            UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"警告" message:@"好友名不可为空" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            [alertC addAction:action];
            [self presentViewController:alertC animated:YES completion:^{
                
            }];
        }
        //附加信息为空
        NSString *text = (descriptionField.text.length == 0) ? @"我想加你好友" : descriptionField.text;
        BOOL result = [[EaseMob sharedInstance].chatManager addBuddy:userNameField.text message:text error:nil];
        if (result) {
            UIAlertController *alertD = [UIAlertController alertControllerWithTitle:@"好友申请成功" message:nil preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *aaction = [UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            [alertD addAction:aaction];
            [self presentViewController:alertD animated:YES completion:^{
                
            }];
            
        }else{
            NSLog(@"添加失败");
            
        }
        
    }];
    
    //取消按钮
    UIAlertAction *canleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:sureAction];
    [alert addAction:canleAction];
    [self presentViewController:alert animated:YES completion:^{
        
    }];
    //设置代理方法
    [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:nil];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSMutableArray *array = [NSMutableArray array];
    NSString *key = [_groupArray objectAtIndex:section];
    for (EMBuddy *buddy in _buddyList) {
        if ([key isEqualToString:[buddy.username substringToIndex:1]]) {
            [array addObject:buddy.username];
        }
    }
    return array.count;;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    EMBuddy *buddy = self.buddyList[indexPath.section];
    cell.textLabel.text = buddy.username;
    return cell;
}
//协议方法 通讯录改变时调用
-(void)didUpdateBuddyList:(NSArray *)buddyList changedBuddies:(NSArray *)changedBuddies isAdd:(BOOL)isAdd{
    self.buddyList = buddyList;
    [_tableView reloadData];
    
}
//被好友删除时调用
-(void)didRemovedByBuddy:(NSString *)username{
    NSLog(@"我被%@删除了", username);
}
//tableView删除方法
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    EMBuddy *buddy = self.buddyList[indexPath.row];
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        BOOL result = [[EaseMob sharedInstance].chatManager removeBuddy:buddy.username removeFromRemote:YES error:nil];
        if (result) {
            NSLog(@"删除成功");
            
        }else{
            NSLog(@"删除失败");
            
        }
        
    }
}
//分组名
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    return [_groupArray objectAtIndex:section];
    
}
-(CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 10;
}

//侧边栏
-(NSArray <NSString *>*)sectionIndexTitlesForTableView:(UITableView *)tableView{
    return _groupArray;
    
}
//分区数
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _groupArray.count;
}
//获得头文字D  ----------------------===============---------------------------------
-(NSArray<NSString *> *)getGroupNames{
    self.groupArray = [NSMutableArray array];
    for (EMBuddy *buddy in _buddyList) {
        NSString *str = [buddy.username substringToIndex:1];
        [_groupArray addObject:str];
    }
    return _groupArray;
    
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
   
    self.hidesBottomBarWhenPushed = YES;
    CharDetailViewController *vc = [[CharDetailViewController alloc] init];
    vc.buddy = [_buddyList objectAtIndex:indexPath.section];
   
    [self.navigationController pushViewController:vc animated:YES];
    
    self.hidesBottomBarWhenPushed = NO;
    
}
//即将自动连接
-(void)willAutoReconnect{
    
    NSLog(@"即将自动连接");
    self.title = @"即将自动连接...";
    
}

//自动连接成功

-(void)didAutoReconnectFinishedWithError:(NSError *)error{
    
    NSLog(@"自动连接成功");
    self.title = @"通讯录";
    
}

//监听状态的改变4

-(void)didConnectionStateChanged:(EMConnectionState)connectionState{
    switch (connectionState) {
        case eEMConnectionConnected:
        {
            
            self.title = @"连接成功";
        }
            break;
        case eEMConnectionDisconnected:
            
        {
            self.title = @"快信（未连接）";
            
        }
            break;
            
        default:
            break;
    }
    
    NSLog(@"类型为 = %zd",connectionState);
}



@end